package Controllers;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;

import Bean.BeanBook;
import Impl.BookServiceImpl;
import exception.BooksNotFoundException;

/**
 * Servlet implementation class ShowCategory
 */
@Controller
public class ShowCategoryController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	BookServiceImpl bookService;
    /**
     * @throws BooksNotFoundException 
     * @see HttpServlet#HttpServlet()
     */
	@RequestMapping("/ShowCategory")
	  public void handleRequest(HttpServletRequest request, HttpServletResponse response)
	            throws ServletException, IOException, BooksNotFoundException {
			JSONArray arr = new JSONArray();
	    	ApplicationContext applicationContext=(ApplicationContext)request.getSession().getServletContext().getAttribute("ctx");
	        bookService=(BookServiceImpl)applicationContext.getBean("BookServiceImpl");
	        int category=Integer.parseInt(request.getParameter("category").replaceAll("'", ""));
			Collection<BeanBook>books= bookService.getByCategory(category);
			for(BeanBook book : books) {
				arr.add(book.toJson());
			}
			response.getWriter().append(arr.toJSONString()); 
	    }

}
